package com.louis.iread.ui;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.AppCompatButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.louis.iread.R;
import com.louis.iread.adapter.BookListAdapter;
import com.louis.iread.adapter.NovelOpAdapter;
import com.louis.iread.adapter.NovelOpOption;
import com.louis.iread.bean.Book;
import com.louis.iread.bean.BookMgr;
import com.louis.iread.bean.Config;
import com.louis.iread.event.EventType;
import com.louis.iread.event.ReadEvent;
import com.louis.iread.skin.SkinMgr;
import com.louis.iread.utils.ConstValue;
import com.louis.iread.utils.DbUtil;
import com.louis.iread.utils.ScreenUtils;
import com.louis.iread.utils.SimpleTask;
import com.louis.iread.utils.ThreadPool;
import com.yarolegovich.lovelydialog.LovelyChoiceDialog;
import com.yarolegovich.lovelydialog.LovelyDialogCompat;
import com.yarolegovich.lovelydialog.LovelyStandardDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;

public class BooksheftFrm extends Fragment {
    private static final String ARG_TAG = "booksheft";
    private SwipeRefreshLayout mPullToRefreshView;
    private ListView mBookListView;
    public static final int REFRESH_DELAY = 2000;

    public BooksheftFrm() {
        // Required empty public constructor
    }

    public static BooksheftFrm newInstance(String tag) {
        BooksheftFrm fragment = new BooksheftFrm();
        Bundle args = new Bundle();
        args.putString(ARG_TAG, tag);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void updateBooks() {
        List<Book> books = BookMgr.getMgr().getBooks();
        for (final Book book : books) {
            ThreadPool.getInstance().commit(new Runnable() {
                @Override
                public void run() {
                    book.updateArticles();
                    EventBus.getDefault().post(new ReadEvent(EventType.BOOK_UPDATE_FINISH));
                }
            });
        }
    }

    public void updateBook(int bookId) {
        final Book book = BookMgr.getMgr().getBooks().get(bookId);
        if (book == null) {
            return;
        }
        ThreadPool.getInstance().commit(new Runnable() {
            @Override
            public void run() {
                book.updateArticles();
                EventBus.getDefault().post(new ReadEvent(EventType.BOOK_UPDATE_FINISH));
            }
        });
    }

    public void downloadRemainArticles(int bookId) {
        final Book book = BookMgr.getMgr().getBooks().get(bookId);
        if (book == null) {
            return;
        }
        ThreadPool.getInstance().commit(new Runnable() {
            @Override
            public void run() {
                book.downloadRemainderArticleContent();
                EventBus.getDefault().post(new ReadEvent(EventType.BOOK_UPDATE_FINISH));
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View booksheftView = inflater.inflate(R.layout.fragment_booksheft, container, false);

        mPullToRefreshView = (SwipeRefreshLayout) booksheftView.findViewById(R.id.pull_to_refresh);
        //1 设置进度条的颜色主题，最多能设置四种 加载颜色是循环播放的，只要没有完成刷新就会一直循环
        mPullToRefreshView.setColorSchemeColors(
                Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW
        );
        //2 设置圆圈大小
        mPullToRefreshView.setSize(ScreenUtils.dpToPxInt(50));
        //3 设置圆圈背景颜色
        mPullToRefreshView.setProgressBackgroundColorSchemeResource(R.color.darkGreen);
        mPullToRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPullToRefreshView.setRefreshing(false);
                    }
                }, 4000);

                updateBooks();
            }
        });

        List<Book> books = new ArrayList<>();
        try {

            List<Book> bookList = DbUtil.getDbManager().selector(Book.class).orderBy("readTime", true).findAll();
            if (bookList != null) {
                books.addAll(bookList);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }

        //自动更新
        if (Config.getUpdateOnStart()) {
            updateBooks();
        }

        mBookListView = (ListView) booksheftView.findViewById(R.id.novel_list);
        mBookListView.setAdapter(new BookListAdapter(getActivity(), R.layout.book_list_item, com.louis.iread.BR.book));
        mBookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), ReadActivity.class);
                long id = BookMgr.getMgr().getBooks().get(i).getId();
                intent.putExtra(ConstValue.BOOK_INDEX, id);
                getActivity().startActivity(intent);
            }
        });
        mBookListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
                List<NovelOpOption> opOptionList = new ArrayList<NovelOpOption>();
                opOptionList.add(new NovelOpOption(R.string.novel_detail));
                opOptionList.add(new NovelOpOption(R.string.download_remainder));
                opOptionList.add(new NovelOpOption(R.string.update_text));
                opOptionList.add(new NovelOpOption(R.string.delete_text));
                ArrayAdapter<NovelOpOption> novelOpOptionArrayAdapter = new NovelOpAdapter(getActivity(), opOptionList);
                Book book = (Book) mBookListView.getAdapter().getItem(i);
                new LovelyChoiceDialog(getActivity())
                        .setTitle(book.getNovelName())
                        .setIcon(R.drawable.ic_star_border_white_36dp)
                        .setItems( novelOpOptionArrayAdapter, new LovelyChoiceDialog.OnItemSelectedListener<NovelOpOption>() {
                            @Override
                            public void onItemSelected(int position, NovelOpOption item) {
                                doNovelOperation(i, position, item);
                            }
                        })
                        .show();
                return true;
            }
        });

        AppCompatButton searchButton = (AppCompatButton) booksheftView.findViewById(R.id.search);
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), SearchActivity.class);
                startActivity(intent);
            }
        });

        EventBus.getDefault().register(this);

        return booksheftView;
    }

    public void doNovelOperation(final int novelListId, int position, NovelOpOption item) {
        final Book book = ( Book)mBookListView.getAdapter().getItem(novelListId);
        if (item.strId == R.string.delete_text) {
            //删除小说
            new LovelyStandardDialog(getActivity())
                    .setButtonsColorRes(R.color.darkDeepOrange)
                    .setIcon(R.drawable.ic_star_border_white_36dp)
                    .setTitle(R.string.delete_ask)
                    .setMessage(book.getNovelName())
                    .setPositiveButton(android.R.string.ok, LovelyDialogCompat.wrap(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new SimpleTask(getContext(), true){
                                @Override
                                public void doOnPreExe() {

                                }

                                @Override
                                public void doOnPublish(Object ojb) {

                                }

                                @Override
                                public Integer doOnBackgroundExe() {
                                    BookMgr.getMgr().removeBook(book.getId());
                                    EventBus.getDefault().post(new ReadEvent(EventType.REMOVE_BOOK));
                                    return 1;
                                }

                                @Override
                                public void doOnComplete(Integer result) {
                                }
                            }.execute();


                        }
                    }))
                    .setNegativeButton(android.R.string.no, null)
                    .show();
        } else if (item.strId == R.string.novel_detail) {
            //打开小说详情页面
            Context context = getActivity();
            Intent intent = new Intent(context, NovelInfoActivity.class);
            intent.putExtra(ConstValue.BOOK_INDEX, book.getId());
            context.startActivity(intent);
        } else if (item.strId == R.string.update_text) {
            Toast.makeText(getActivity(), R.string.update_contents, Toast.LENGTH_SHORT).show();
            updateBook(novelListId);
        } else  if (item.strId == R.string.download_remainder) {
            Toast.makeText(getActivity(), R.string.download_remainder_bg, Toast.LENGTH_SHORT).show();
            downloadRemainArticles(novelListId);
        }
    }

    @Override
    public void onHiddenChanged (boolean hidden) {
        if (!hidden) {
            ((BookListAdapter) mBookListView.getAdapter()).updateBookList();
            ((BookListAdapter) mBookListView.getAdapter()).sortBooks();
            ((BookListAdapter) mBookListView.getAdapter()).notifyDataSetChanged();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(ReadEvent event) {
        switch (event.getEventType()) {
            case UPDATE_BOOK_LIST:
            case BOOK_UPDATE_FINISH:
                ((BookListAdapter) mBookListView.getAdapter()).sortBooks();
                ((BookListAdapter) mBookListView.getAdapter()).notifyDataSetChanged();
                break;
            case ADD_BOOK:
            case REMOVE_BOOK:
                ((BookListAdapter) mBookListView.getAdapter()).updateBookList();
                ((BookListAdapter) mBookListView.getAdapter()).sortBooks();
                ((BookListAdapter) mBookListView.getAdapter()).notifyDataSetChanged();
                break;
            default:
                break;
        }
    }

    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            return;
        }
        SkinMgr.getInstance().applyView(view);
    }
}
